/**
 * Created by zheng on 2018/1/7.
 */

let messageConstant =  require('../constant/messageConstant');
let utilConstant =require('../constant/utilConstant');
let jwt = require('jwt-simple');
let typeUtil = require('../util/util-lang');

exports.login = function (req, res) {
  if (req.header.Authorization) {

  }
  else {
    let result = {};
    //use to avoid repeat judgement
    let flag = true;

    //has token
    if(!typeUtil.isUndefined(req.cookies['token'])){
      console.log('header...',req.cookies);
      let resultPayload = jwt.decode(req.cookies['token'],utilConstant.SECRET,true,utilConstant.USE_TO_JWT_ALGORITHMN);
      if(verifyAccountWithTokenPayload(resultPayload)){
        result.result = 'success';
      }
      flag = false;
    }

    let payload = {};
    let data = req.body;
    let username = data.username;
    let password = data.password;
    //no username or no password
    if (flag&&typeUtil.isUndefined(username) || typeUtil.isUndefined(password)) {
      result.result = "fail";
      result.message = messageConstant.MESSAGE_NO_USERNAME_PASSWORD;
      flag =false;
    }

    //verify username and password
    if(flag) {
      if (verifyAccountWithNameAndPwd(username,password)) {
        payload.username = username;
        let token = jwt.encode(payload, utilConstant.SECRET, utilConstant.USE_TO_JWT_ALGORITHMN);
        result.result = 'success';
        //secure use for https,because of our server don't use it so that is false
        //domain for token use domain
        res.cookie('token', token, {httpOnly: true, domain:'localhost', secure:false});
      } else {

        result.result = 'fail';
        result.message = messageConstant.MESSAGE_USERNAME_PASSWORD_NOT_CORRECT;
      }
    }
    res.json({result});
  }
}

let verifyAccountWithNameAndPwd = (username, password) => {
  return username == 'ZHENGGE' && password == 'PasswordB5';
}

let verifyAccountWithTokenPayload = (payload) => {
  return payload.username == 'ZHENGGE';
}
